[javascript] Can I overload an object with a function?

Posted by user257493 on Stack Overflow See other posts from Stack Overflow or by user257493
Published on 2011-02-09T15:18:29Z Indexed on 2011/02/09 15:25 UTC
Read the original article Hit count: 139

Lets say I have an object of functions/values. I'm interested in overloading based on calling behavior.

For example, this block of code below demonstrates what I wish to do.

var main_thing = {
    initalized: false,
    something: "Hallo, welt!",
    something_else: [123,456,789],
    load: {
        sub1    : function() {
            //Some stuff
        },
        sub2    : function() {
            //Some stuff
        },
        all     : function() {
            this.load.sub1();
            this.load.sub2();
        }
    }
    init: function () {
        this.initalized=true;
        this.something="Hello, world!";
        this.something_else = [0,0,0];
        this.load(); //I want this to call this.load.all() instead.
    }
}

The issue to me is that main_thing.load is assigned to an object, and to call main_thing.load.all() would call the function inside of the object (the () operator). What can I do to set up my code so I could use main_thing.load as an access the object, and main_thing.load() to execute some code? Or at least, similar behavior.

Basically, this would be similar to a default constructor in other languages where you don't need to call main_thing.constructor().

If this isn't possible, please explain with a bit of detail.

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about object